import mysql.connector
import json

list_admin = []

json_data = json.load(open('./routers.json', encoding='utf-8'))

def get_field(json_data):
    for item in json_data:
        if "children" in item.keys():
            get_field(item.get('children'))
        list_admin.append({'path': item['path'], 
               'name': item.get('name',''), 
               'component': item.get('component',''), 
               'title': item.get('meta').get('title') if item.get('meta') else '', 
               'icon': item.get('meta').get('icon') if item.get('meta') else '',
               'is_hidden': item.get('is_hidden',False)})



def insert_db(data_list_map):
    cnx = mysql.connector.connect(user='root', password='123456',
                                host='localhost',
                                port=3306,
                                database='report')
    with cnx.cursor() as cursor:
        sql = "insert into sys_menu (path, name, component, title, icon, is_hidden, parent_id) values (%s, %s, %s, %s, %s, %s, 0)"
        cursor.executemany(sql, [[item['path'],
                              item['name'],
                              item['component'],
                              item['title'], 
                              item['icon'],
                              item['is_hidden']]
                              for item in data_list_map])
        
    cnx.commit()
    cnx.close()


get_field(json_data.get("admin"))
print(list_admin)
insert_db(list_admin)